<template>
    <div>
        <p>
            <el-input v-model="searchTitle" placeholder="请输入歌曲名称" clearable style="width: 300px;"></el-input>
            <el-button type="success" @click="query">查询</el-button>
            <el-button type="primary" @click="handleAdd">新增歌曲</el-button>
        </p>
        <el-table :data="tableData" style="width: 100%" border stripe>
            <el-table-column prop="id" label="编号" width="180"></el-table-column>
            <el-table-column prop="title" label="歌曲名称" width="180"></el-table-column>
            <el-table-column prop="pic" label="歌曲图片">
                <template slot-scope="scope">
                    <img :src="getImageUrl(scope.row.pic)" style="width: 80px;height: 80px;" :alt="scope.row.title" />
                </template>
            </el-table-column>
            <el-table-column prop="releaseTime" label="发行时间"></el-table-column>
            <el-table-column prop="style" label="歌曲风格"></el-table-column>
            <el-table-column prop="singerId" label="歌手ID" width="120"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                    <el-popconfirm title="确定删除该歌曲吗？删除后不可恢复！" @confirm="handleDelete(scope.$index, scope.row)">
                        <el-button size="mini" slot="reference" type="danger">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange" 
            :current-page="pageNum"
            :page-sizes="[4, 10, 20, 50]" 
            :page-size="pageSize" 
            layout="total, sizes, prev, pager, next, jumper" 
            :total="total"
            style="margin-top: 20px; text-align: right;"
        ></el-pagination>

        <el-dialog title="歌曲信息" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-form ref="songForm" :model="form" label-width="80px" :rules="formRules">
                <el-form-item label="歌曲图片">
                    <el-upload 
                        class="avatar-uploader" 
                        action="http://localhost:8085/music/file/song/upload"
                        :show-file-list="false" 
                        :on-success="handleAvatarSuccess" 
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="imageUrl || form.pic" :src="imageUrl || getImageUrl(form.pic)" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="歌曲名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="歌手ID" prop="singerId">
                    <el-input v-model.number="form.singerId" type="number"></el-input>
                </el-form-item>
                <el-form-item label="发行时间" prop="releaseTime">
                    <el-date-picker
                        v-model="form.releaseTime"
                        type="date"
                        value-format="yyyy-MM-dd"   
                        format="yyyy-MM-dd"       
                        placeholder="选择发行时间"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="歌曲风格" prop="style">
                    <el-input v-model="form.style"></el-input>
                </el-form-item>
                <el-form-item label="歌曲介绍" prop="introduction">
                    <el-input v-model="form.introduction" type="textarea" :rows="3"></el-input>
                </el-form-item>
                <el-form-item label="歌曲地址" prop="url">
                    <el-input v-model="form.url" placeholder="如 /music/song/xxx.mp3"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import request from '../utils/request';

export default {
    name: 'SongList',
    data() {
        return {
            tableData: [],
            dialogVisible: false,
            form: {
                id: '',
                title: '',
                singerId: '',
                releaseTime: null,
                style: '',
                introduction: '',
                pic: '',
                url: ''
            },
            imageUrl: '', // 上传图片的临时预览地址
            searchTitle: '', // 搜索关键字（避免与form.title冲突）
            pageNum: 1,
            pageSize: 4, // 统一命名为pageSize，与后端参数对应
            total: 0,
            // 表单校验规则
            formRules: {
                title: [
                    { required: true, message: '请输入歌曲名称', trigger: 'blur' },
                    { min: 1, max: 50, message: '歌曲名称长度在1-50个字符之间', trigger: 'blur' }
                ],
                singerId: [
                    { required: true, message: '请输入歌手ID', trigger: 'blur' },
                    { type: 'number', message: '歌手ID必须为数字', trigger: 'blur' }
                ],
                releaseTime: [
                    { required: true, message: '请选择发行时间', trigger: 'change' }
                ],
                style: [
                    { required: true, message: '请输入歌曲风格', trigger: 'blur' },
                    { min: 1, max: 20, message: '歌曲风格长度在1-20个字符之间', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: '请输入歌曲地址', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.query();
    },
    methods: {
        // 拼接图片完整路径
        getImageUrl(path) {
            if (!path) return '';
            return "http://localhost:8085" + path;
        },
        // 图片上传成功回调
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.form.pic = res.path;
        },
        // 图片上传前校验
        beforeAvatarUpload(file) {
            const isImage = file.type.startsWith('image/');
            const isJPGOrPNG = (file.type === 'image/jpeg') || (file.type === 'image/png');
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (!isImage) {
                this.$message.error('请上传图片文件！');
                return false;
            }
            if (!isJPGOrPNG) {
                this.$message.error('上传图片只能是 JPG/png 格式!');
                return false;
            }
            if (!isLt10M) {
                this.$message.error('上传图片大小不能超过 10MB!');
                return false;
            }
            return true;
        },
        // 每页条数变更
        handleSizeChange(val) {
            this.pageSize = val;
            this.query();
        },
        // 页码变更
        handleCurrentChange(val) {
            this.pageNum = val;
            this.query();
        },
        // 新增歌曲
        handleAdd() {
            this.dialogVisible = true;
            this.imageUrl = '';
            // 重置表单
            this.$nextTick(() => {
                this.$refs.songForm.resetFields();
            });
            this.form = {
                id: '',
                title: '',
                singerId: '',
                releaseTime: null,
                style: '',
                introduction: '',
                pic: '',
                url: ''
            };
        },
        // 查询歌曲列表
        query() {
            request.get("/song/list", {
                params: {
                    title: this.searchTitle,
                    pageNum: this.pageNum,
                    size: this.pageSize,
                }
            }).then((res) => {
                if (res.success) {
                    this.tableData = res.list || [];
                    this.total = res.total || 0;
                } else {
                    this.$message.error('查询失败：' + (res.message || '未知错误'));
                }
            }).catch((error) => {
                console.error('查询歌曲列表失败：', error);
                this.$message.error('网络异常，查询失败');
            });
        },
        // 提交表单（新增/修改）
        submitForm() {
            this.$refs.songForm.validate((isValid) => {
                if (isValid) {
                    request.post("/song/update", this.form).then((res) => {
                        if (res.success) {
                            this.$message({ message: res.message || '操作成功', type: 'success' });
                            this.dialogVisible = false;
                            this.query();
                        } else {
                            this.$message.error('操作失败：' + (res.message || '未知错误'));
                        }
                    }).catch((error) => {
                        console.error('提交歌曲信息失败：', error);
                        this.$message.error('网络异常，提交失败');
                    });
                } else {
                    this.$message.warning('请完善表单必填项');
                    return false;
                }
            });
        },
        // 编辑歌曲
        handleEdit(index, row) {
            this.dialogVisible = true;
            this.imageUrl = '';
            // 赋值表单数据
            this.form = { ...row };
            // 处理日期格式（确保与日期选择器兼容）
            this.form.releaseTime = row.releaseTime ? new Date(row.releaseTime) : null;
        },
        // 删除歌曲
        handleDelete(index, row) {
            request.get("/song/delete?id=" + row.id).then((res) => {
                if (res.success) {
                    this.$message({ message: res.message || '删除成功', type: 'success' });
                    this.query();
                } else {
                    this.$message.error('删除失败：' + (res.message || '未知错误'));
                }
            }).catch((error) => {
                console.error('删除歌曲失败：', error);
                this.$message.error('网络异常，删除失败');
            });
        },
        // 关闭对话框
        handleClose(done) {
            this.$confirm('确认关闭吗？未保存的内容将丢失').then(_ => {
                done();
            }).catch(_ => {});
        }
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}
</style>